<script lang="ts" setup>
import type { NotificationItem } from '@vben/layouts';

import { computed, onBeforeMount, ref, watch } from 'vue';

import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
import { VBEN_DOC_URL, VBEN_BLUESHARK_URL } from '@vben/constants';
import { useWatermark } from '@vben/hooks';
import { InfoModel, BlueShark } from '@vben/icons';
import {
  BasicLayout,
  LockScreen,
  Notification,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useTabbarStore, useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';
import { useVbenDrawer } from '@vben/common-ui';

import { $t } from '#/locales';
import { useAuthStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';

const { setMenuList } = useTabbarStore();
setMenuList([
  'close',
  'affix',
  'maximize',
  'reload',
  'open-in-new-window',
  'close-left',
  'close-right',
  'close-other',
  'close-all',
]);

const notifications = ref<NotificationItem[]>([
  {
    avatar: 'https://avatar.vercel.sh/vercel.svg?text=VB',
    date: '3小时前',
    isRead: true,
    message: '描述信息描述信息描述信息',
    title: '收到了 14 份新周报',
  },
  {
    avatar: 'https://avatar.vercel.sh/1',
    date: '刚刚',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '朱偏右 回复了你',
  },
  {
    avatar: 'https://avatar.vercel.sh/1',
    date: '2024-01-01',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '曲丽丽 评论了你',
  },
  {
    avatar: 'https://avatar.vercel.sh/satori',
    date: '1天前',
    isRead: false,
    message: '描述信息描述信息描述信息',
    title: '代办提醒',
  },
]);

const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
  notifications.value.some((item) => !item.isRead),
);
import Form from './modules/form.vue';

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});
import { message } from 'ant-design-vue';
import type { SystemUserApi } from '#/api';
import { getUserRoleList,getUserInfoApi } from '#/api';

async function onEdit(row: SystemUserApi.SystemUser) {
  try {
    // 获取用户角色列表
    const roleList = await getUserRoleList(row.id);
    // 将用户信息和角色信息一起传递给表单
    formDrawerApi.setData({
      ...row,
      roleIds: roleList
    }).open();
  } catch (error) {
    message.error('获取用户角色信息失败');
  }
}

const menus = computed(() => [
  {
    handler: async () => {
      // 获取用户信息
      const rowInfo = await getUserInfoApi();
      // 补全 SystemUser 必需字段
      const systemUser: SystemUserApi.SystemUser = {
        id: String((rowInfo as any).id ?? (rowInfo as any).userId ?? ''),
        username: (rowInfo as any).username ?? '',
        realName: (rowInfo as any).realName ?? '',
        email: (rowInfo as any).email ?? '',
        phone: (rowInfo as any).phone ?? '',
        avatar: (rowInfo as any).avatar ?? '',
        status: typeof (rowInfo as any).status === 'number' ? (rowInfo as any).status : 1,
      };
      await onEdit(systemUser);
    },
    icon: InfoModel,
    text: $t('ui.widgets.userInfo'),
  },
  {
    handler: () => {
      openWindow(VBEN_BLUESHARK_URL, {
        target: '_blank',
      });
    },
    icon: BlueShark,
    text: $t('ui.widgets.official'),
  },
]);

const avatar = computed(() => {
  return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
});

async function handleLogout() {
  await authStore.logout(false);
}

function handleNoticeClear() {
  notifications.value = [];
}

function handleMakeAll() {
  notifications.value.forEach((item) => (item.isRead = true));
}

function handleClickLogo() {}

watch(
  () => preferences.app.watermark,
  async (enable) => {
    if (enable) {
      await updateWatermark({
        content: `${userStore.userInfo?.username} - ${userStore.userInfo?.realName}`,
      });
    } else {
      destroyWatermark();
    }
  },
  {
    immediate: true,
  },
);

onBeforeMount(() => {
  if (preferences.app.watermark) {
    destroyWatermark();
  }
});

function onRefresh() {
  window.location.reload(); //刷新页面数据
}
</script>

<template>
  <BasicLayout
    @clear-preferences-and-logout="handleLogout"
    @click-logo="handleClickLogo"
  >
    <template #user-dropdown>
      <UserDropdown
        :avatar
        :menus
        :text="userStore.userInfo?.realName"
        description="ann.vben@gmail.com"
        tag-text="Pro"
        trigger="both"
        @logout="handleLogout"
      />
    </template>
    <template #notification>
      <Notification
        :dot="showDot"
        :notifications="notifications"
        @clear="handleNoticeClear"
        @make-all="handleMakeAll"
      />
    </template>
    <template #extra>
      <AuthenticationLoginExpiredModal
        v-model:open="accessStore.loginExpired"
        :avatar
      >
        <LoginForm />
      </AuthenticationLoginExpiredModal>
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
  <FormDrawer @success="onRefresh" />
</template>
